<!-- 新增/编辑 组织机构 -->
<template>
  <ve-modal v-model="visible" title="修改承租人信息" :okLoading="okLoading" cancelText="取消" @cancel="onCancel" @confirm="onConfirm">
    <ve-form class="edit-form" :rules="formRules" :model="form" layout="vertical" ref="formRef">
      <customer ref="customerRef" mode="edit" mode2="editMemberModal" />
    </ve-form>
  </ve-modal>
</template>

<script setup>
  import { ref, provide, computed } from 'vue'
  import { getOrdrDetailsAPI, editMemberInfoAPI } from '@/api/order/lOrder'
  import { findByPhoneAPI } from '@/api/order/order'
  import { usePageDict } from '@/hooks/useDict'
  import useToast from '@/hooks/useToast'
  import customer from '@/pages/order/components/customer/index.vue'
  const dict = usePageDict('longOrderDict')
  provide('dict', dict)
  const emits = defineEmits(['ok'])
  const visible = ref(false)
  const form = ref({})
  provide('form', form)

  const formRules = computed(() => {
    let tempRules = {
      memberType: { required: true, message: '请选择客户类型' },
      memberPhone: [
        { required: true, message: '请输入联系电话' },
        { len: 11, match: /^[0-9]+$/, message: '仅支持数字，长度11位' },
      ],
      memberName: { required: true, message: '请输入承租人' },
      cardNumber: { match: /^[a-zA-Z0-9]+$/, message: '支持数字、英文' },
    }

    // 客户类型为公司客户
    if (form.value.memberType == 1) {
      tempRules.clientId = { required: true, message: '请选择客户公司名称' }
    }

    return tempRules
  })

  const customerRef = ref()
  const open = (orderId, editData = undefined) => {
    visible.value = true
    getOrdrDetailsAPI({ id: orderId }).then(({ result }) => {
      const orderInfo = result.orderInfo
      const memberInfoDto = result.memberInfoDto
      // 更新 form
      form.value = {
        id: orderId,
        memberType: orderInfo.memberType,
        memberTypeName: orderInfo.memberTypeName,
        // 个人用户
        memberPhone: orderInfo.memberPhone,
        memberName: orderInfo.memberName,
        // 企业用户
        clientId: orderInfo.clientId,
        clientName: orderInfo.clientName,
        memberId: orderInfo.memberId,
        // 通用
        cardType: memberInfoDto.cardType || 0,
        cardNumber: memberInfoDto.cardNumber,
        cardAddress: memberInfoDto.cardAddress,
        // 驾驶证正反面信息
        driverFrontFileId: memberInfoDto.driverFrontFileId,
        driverReverseFileId: memberInfoDto.driverReverseFileId,
        // 身份证明正反面信息
        idCardFrontFileId: memberInfoDto.idCardFrontFileId,
        idCardReverseFileId: memberInfoDto.idCardReverseFileId,
        // 紧急联系人
        emergencyContactName: memberInfoDto.emergencyContactName,
        emergencyContactPhone: memberInfoDto.emergencyContactPhone,
      }
      if (editData) {
        findByPhoneAPI({ phone: editData.memberPhone }).then(({ result }) => {
          form.value.cardType = result.cardType || 0
          form.value.cardNumber = result.cardNumber
          form.value.cardAddress = result.cardAddress
          form.value.memberPhone = editData.memberPhone
          form.value.memberName = editData.memberName
          form.value.clientId = result.clientId
          form.value.memberId = result.memberId
          form.value.driverFrontFileId = result?.driverFrontFileId
          form.value.driverReverseFileId = result?.driverReverseFileId
          form.value.idCardFrontFileId = result?.idCardFrontFileId
          form.value.idCardReverseFileId = result?.idCardReverseFileId
          // 紧急联系人
          form.value.emergencyContactName = result.emergencyContactName
          form.value.emergencyContactPhone = result.emergencyContactPhone
        })
      }
      // 更新显示上传驾驶证按钮
      customerRef.value.updateUploadDriverBtnStatus(!form.value.driverFrontFileId || !form.value.driverReverseFileId)
      // 更新显示上传身份证明按钮
      customerRef.value.updateUploadIdCardBtnStatus(
        !form.value.idCardFrontFileId || (form.value.cardType == 0 && !form.value.idCardReverseFileId),
      )
      customerRef.value.updateMemberInfo(memberInfoDto)
    })
  }

  const onCancel = () => {
    visible.value = false
  }
  // 等待 customer 组件接口调用完成
  const waitCustomerDone = () => {
    return new Promise((resolve) => {
      setTimeout(() => {
        let fetching = customerRef.value.memberPhoneFetching
        if (fetching) {
          customerRef.value.waitMemberPhoneFetchingDone(() => {
            resolve()
          })
        } else {
          resolve()
        }
      }, 0)
    })
  }
  const formRef = ref()
  const okLoading = ref(false)

  const onConfirm = () => {
    formRef.value.validate((valid) => {
      if (valid) {
        okLoading.value = true
        const param = {
          ...form.value,
        }
        // 监听 customer 组件 memberPhoneFetching 完成
        waitCustomerDone().then(() => {
          editMemberInfoAPI(param).then(() => {
            useToast({
              title: '保存成功',
            }).then(() => {
              visible.value = false
              emits('ok')
              okLoading.value = false
            }).catch(() => {
              okLoading.value = false
            })
          })
        })
      }
    })
  }
  defineExpose({
    open,
  })
</script>

<style lang="less" scoped>
  .edit-form {
    /deep/ .ve-card {
      box-shadow: none;
      margin-bottom: 0;
      .ve-card-header {
        display: none;
      }
      .ve-card-content {
        padding: 0;
      }
    }
  }
</style>
